<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" v-model="listQuery" class="search" size="mini">
        <el-row>
          <el-col :span="3">
            <el-form-item label="">
              <el-select
                v-model="listQuery.supplier"
                placeholder="供应商"
                clearable
              >
                <el-option
                  v-for="item in suppliers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="">
              <el-date-picker
                v-model="listQuery.search_date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click.native="handleFilter"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="success"
                icon="el-icon-download"
                size="mini"
                @click.native="handleExport"
                >导出</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 上部 -->
      <el-row>
        <el-col :span="18" :offset="3">
          <h3 style="text-align: center; margin: 20px">
            {{ supplier && supplier.name }}对账单
          </h3>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18" :offset="3">
          <div style="text-align: center; margin: 10px">
            对账日期: {{ listQuery.search_date[0] }}至{{
              listQuery.search_date[1]
            }}
          </div>
        </el-col>
      </el-row>
      <el-row v-if="supplier != null">
        <el-col :span="6" :offset="4">
          <div class="sub_title">供应商: {{ supplier && supplier.name }}</div>
        </el-col>
        <el-col :span="6">
          <div class="sub_title">
            联系人: {{ supplier && supplier.linkman }}
          </div>
        </el-col>
        <el-col :span="6">
          <div class="sub_title">传真: {{ supplier && supplier.fax }}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18" :offset="3">
          <el-table
            :data="datas"
            border
            stripe
            v-loading="listLoading"
            highlight-current-row
            style="width: 1300px"
            size="mini"
            max-height="400"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="index" align="center" label="序号">
            </el-table-column>
            <el-table-column
              v-for="column in tableColumns"
              :key="column.key"
              :label="column.title"
              :prop="column.key"
              :align="column.align"
              :width="column.width ? column.width : ''"
              :formatter="dataFormatter"
            >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import moment from "moment";

import { getSupplierList } from "@/api/base";
import { getPurchaseBill, downloadPurchaseBill } from "@/api/purchase";

import { getCurrentDate } from "@/utils/datetime";

export default {
  name: "PurchaseBill",
  data() {
    return {
      company: {},
      supplier: null,
      sums: {},
      tableColumns: [
        {
          key: "entry_code",
          title: "采购入库单编号",
          align: "left",
          width: "140",
        },
        {
          key: "goods_code",
          title: "商品编号",
          align: "center",
          width: "100",
        },
        {
          key: "goods_name",
          title: "商品名称",
          width: "150",
        },
        {
          key: "goods_specs",
          title: "规格",
          align: "center",
          width: "120",
        },
        {
          key: "entry_time",
          title: "日期",
          align: "center",
          width: "100",
        },
        {
          key: "nums",
          title: "入库数量",
          align: "center",
          width: "100",
        },

        {
          key: "price",
          title: "单价",
          align: "center",
          width: "120",
        },
        {
          key: "total_amount",
          title: "金额",
          align: "center",
          width: "120",
        },
        {
          key: "amount",
          title: "已付金额",
          align: "center",
          width: "120",
        },
        {
          key: "nopay_amount",
          title: "未付金额",
          align: "center",
          width: "120",
        },
      ],

      title: "采购入库对账单",

      datas: [],
      suppliers: [],

      listLoading: true,
      finished: false,

      listQuery: {
        supplier: null,
        flag: 0,
        export: 0,
        search_date: [
          moment().add(-30, "days").format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ],
      },
    };
  },

  created() {
    this.getSuppliers();
    this.getBillList();
  },
  methods: {
    getSuppliers() {
      getSupplierList().then((res) => {
        this.suppliers = res;
      });
    },

    getBillList() {
      this.listQuery.export = 0;
      this.listLoading = true;
      getPurchaseBill(this.listQuery)
        .then((res) => {
          this.datas = res.data;
          this.company = res.company;
          this.supplier = res.supplier;
          this.sums = res.sums;
          this.listLoading = false;
          this.finished = true;
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
          this.listLoading = false;
          this.finished = true;
        });
    },

    // 查询
    handleFilter() {
      this.datas = [];
      this.getBillList();
    },
    handleExport() {
      this.listQuery.export = 1;
      downloadPurchaseBill(this.listQuery)
        .then((res) => {
          // console.log(res);
          if (res.data.type === "application/octet-stream") {
            let filename = res.headers["content-disposition"];
            const blob = new Blob([res.data]);
            let downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = decodeURI(filename.split("filename=")[1]); //下载后文件名

            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          }
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
        });
    },
    dataFormatter(row, column, cellValue, index) {
      if (
        column.property === "total_amount" ||
        column.property === "amount" ||
        column.property === "nopay_amount"
      ) {
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (!this.sums) return;

        if (column.property === "total_amount") {
          sums[index] = parseFloat(this.sums.total_amount || 0).toFixed(2);
        } else if (column.property === "amount") {
          sums[index] = parseFloat(this.sums.amount || 0).toFixed(2);
        } else if (column.property === "nums") {
          sums[index] = parseInt(this.sums.total_nums || 0);
        } else if (column.property === "nopay_amount") {
          sums[index] = parseFloat(this.sums.nopay_amount || 0).toFixed(2);
        } else {
          return;
        }
      });
      return sums;
    },
  },
};
</script>

<style lang='scss' scoped>
.sub_title {
  font-size: 14px;
  color: #606266;
}
</style>